package com.itany.mall.action;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import com.itany.mall.entity.Order;
import com.itany.mall.entity.OrderDetail;
import com.itany.mall.entity.Product;
import com.itany.mall.entity.User;
import com.itany.mall.exception.OrderNotFoundException;
import com.itany.mall.exception.ProductNotFoundException;
import com.itany.mall.factory.Autowired;
import com.itany.mall.factory.ObjectFactory;
import com.itany.mall.service.OrderService;
import com.itany.mall.service.ProductService;
import com.itany.mall.service.UserService;

public class NormalAction {

	@Autowired
	private UserService userService;

	@Autowired
	private ProductService productService;

	@Autowired
	private OrderService orderService;

	private Map<Long, OrderDetail> shopingCart = new HashMap<>();

	private User loginUser;

	{
		ObjectFactory.autowired(this);
	}

	// 当创建NormalAction对象时
	// 将登录用户传递到这里备用
	// 同时加载用户的购物车信息
	public NormalAction(User loginUser) {
		this.loginUser = loginUser;
		loadCart(); // 加载购物车
	}

	public void menu() {
		do {
			System.out.println("1. 浏览商品");
			System.out.println("2. 选购商品");
			System.out.println("3. 查看购物车");
			System.out.println("4. 查看历史订单");
			System.out.println("5. 退出登录");
			switch (new Scanner(System.in).nextLine()) {
				case "1":
					showProducts();
					break;
				case "2":
					choose();
					break;
				case "3":
					showCart();
					break;
				case "4":
					showMyOrders();
					break;
				case "5":
					// 用户退出时, 保存用户的购物车信息
					// 并将登录用户信息清除
					saveCart();
					loginUser = null;
					return;
				default:
					System.out.println("选择错误");
			}
		} while (true);
	}

	// 查看用户的历史订单
	private void showMyOrders() {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		List<Order> orders = orderService.findMyOrders(loginUser.getId());
		for (Order o : orders) {
			System.out.print("订单编号: " + o.getId() + ", ");
			System.out.print("订单流水号: " + o.getOrderNum() + ", ");
			System.out.print("订单总价: " + o.getPrice() + ", ");
			System.out.println("下单时间: " + df.format(o.getCreateTime()));
		}
		System.out.println("1. 查看订单详情, 退出查看请输入其它内容");
		if ("1".equals(new Scanner(System.in).nextLine())) {
			showOrderDetail();
		}
	}

	// 查看订单详情
	private void showOrderDetail() {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		System.out.println("请输入订单流水号");
		String num = new Scanner(System.in).nextLine();
		if (num == null || num.isEmpty()) {
			System.out.println("订单流水号不可为空");
			return;
		}

		try {
			Map<Order, List<OrderDetail>> ods = orderService.findDetailsByOrderNum(num,
					loginUser.getId());

			for (Map.Entry<Order, List<OrderDetail>> entry : ods.entrySet()) {

				System.out.print("订单编号: " + entry.getKey().getId() + ", ");
				System.out.print("订单流水号: " + entry.getKey().getOrderNum() + ", ");
				System.out.println("下单日期: " + df.format(entry.getKey().getCreateTime()) + ", ");
				System.out.println("---------------------------------------------");
				for (OrderDetail od : entry.getValue()) {
					System.out.print("商品名称: " + od.getProduct().getName() + ", ");
					System.out.print("商品数量: " + od.getProductSum() + ", ");
					System.out.print("商品单价: " + od.getProduct().getPrice() + ", ");
					System.out.println("商品总价: " + od.getPrice());
				}
				System.out.println("---------------------------------------------");
				System.out.println("订单总价: " + entry.getKey().getPrice());
			}

		} catch (OrderNotFoundException e) {
			System.out.println("订单不存在");
		}

	}

	// 保存购物车
	private void saveCart() {
		userService.saveCart(shopingCart);
		shopingCart.clear();
	}

	// 加载购物车
	private void loadCart() {
		shopingCart = userService.loadCart(loginUser.getId());
	}

	// 查看购物车
	private void showCart() {
		double price = 0D;
		for (OrderDetail od : shopingCart.values()) {
			System.out.print("商品名称: " + od.getProduct().getName() + ", ");
			System.out.print("商品数量: " + od.getProductSum() + ", ");
			System.out.print("商品单价: " + od.getProduct().getPrice() + ", ");
			System.out.println("商品总价: " + od.getPrice());
			price += od.getPrice();
		}
		System.out.println("---------------------------------------------------------");
		System.out.println("总价: " + price);
		System.out.println("1. 确认下单; 离开购物车请输入其它内容;");
		switch (new Scanner(System.in).nextLine()) {
			case "1":
				commitOrder();
				break;
		}

	}

	// 确认下单
	private void commitOrder() {
		orderService.commitOrder(shopingCart.values());
		shopingCart.clear();
	}

	// 选购商品
	private void choose() {
		// 选择商品编号
		System.out.println("请选择商品(输入商品编号)");
		String pid = new Scanner(System.in).nextLine();
		if (pid == null || !pid.matches("[\\d]+")) {
			System.out.println("商品编号无效");
			return;
		}
		long productId = Long.parseLong(pid);

		// 将编号对应的商品查询出来
		try {
			Product p = productService.findById(productId);
			// 填写选购数量
			System.out.println("请填写选购数量");
			String sum = new Scanner(System.in).nextLine();
			if (sum == null || !sum.matches("[\\d]+")) {
				System.out.println("选购数量无效");
				return;
			}
			int productSum = Integer.parseInt(sum);
			if (productSum < 1) {
				System.out.println("最少选购1件");
				return;
			}

			// 向购物车中加入
			// 已选商品在购物车中是否已存在
			// 用什么表示购物车?
			// 由于购物车中存储信息与订单详情相仿
			// 所以可用一个存储订单详情的容器来表示购物车
			// 购物车容器如何设计?
			// 用什么类型容器? Collection还是Map?
			// 向购物车中添加选购记录时, 判断购物车中是否已有选购商品
			// 选择用Map集合, 以productId为key, 便于判断是否已包含选购商品

			// 如果购物车中没有所选商品
			if (!shopingCart.containsKey(productId)) {
				// 创建od对象并存入到购物车中
				OrderDetail od = new OrderDetail();
				od.setProduct(p); // 商品
				od.setProductSum(productSum); // 商品数量
				od.setPrice(p.getPrice() * productSum); // 商品总价
				od.setUser(loginUser); // 哪个用户的选购记录
				shopingCart.put(productId, od);
				return;
			}

			// 上面if没满足, 说明购物车中已有所选商品
			// 对购物车中选购信息进行更新
			OrderDetail od = shopingCart.get(productId);
			// 对商品数量及商品总价进行更新
			// 原数量 + 新的选购数量
			od.setProductSum(od.getProductSum() + productSum);
			od.setPrice(p.getPrice() * od.getProductSum());
			shopingCart.put(productId, od);
		} catch (ProductNotFoundException e) {
			System.out.println("所选商品不存在");
		}

	}

	// 浏览商品
	private void showProducts() {
		List<Product> list = productService.findAll();
		for (Product p : list) {
			System.out.print("商品编号: " + p.getId() + ", ");
			System.out.print("商品名称: " + p.getName() + ", ");
			System.out.print("商品单价: " + p.getPrice() + ", ");
			System.out.println("商品类型: " + p.getType().getName());
		}
	}

}
